package main

import (
	"fmt"
	"github.com/antchfx/xpath"
	htmlquery "github.com/antchfx/xquery/html"
	"net/http"
	"strings"
)

func main() {
	url := "http://192.168.0.57:8081/"

	if strings.HasSuffix(url, "/") {
		url = strings.TrimRight(url, "/")
	}
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("http错误：" + err.Error())
		panic(err)
	}

	//body, err := ioutil.ReadAll(resp.Body)
	//if err != nil {
	//	panic(err)
	//}
	//fmt.Println(string(body))

	fmt.Println(resp.StatusCode)
	if resp.StatusCode == 200 {
		fmt.Println("ok")
	}

	// Parse HTML document.
	doc, err := htmlquery.Parse(resp.Body)
	if err != nil {
		panic(err)
	}
	// Option 1: using xpath's expr to matches nodes.
	//expr := xpath.MustCompile("count(//div[@class='article'])")
	//fmt.Printf("%f \n", expr.Evaluate(htmlquery.CreateXPathNavigator(doc)).(float64))

	expr := xpath.MustCompile("//a/@href")
	iter := expr.Evaluate(htmlquery.CreateXPathNavigator(doc)).(*xpath.NodeIterator)
	paths := []string{}
	for iter.MoveNext() {
		//fmt.Printf("%s \n", iter.Current().Value()) // output href
		href := iter.Current().Value()
		if href != "" && href != "\\" && href != "../" {
			paths = append(paths, iter.Current().Value())
		}
	}

	for _, path := range paths {
		fmt.Printf("%s \n", path) // output href
	}

	// Option 2: using build-in functions Find() to matches nodes.
	//for _, n := range htmlquery.Find(doc, "//a/@href") {
	//	fmt.Printf("%s \n", htmlquery.SelectAttr(n, "href")) // output href
	//}

}
